package org.lc.stk.model.question.impl.fillBlank;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 填空题题干格式化工具类
 */
public class FillBlankStemFormatter {
    private static final Pattern BLANK_PATTERN = Pattern.compile("\\{\\{(\\d+)\\}\\}");
    
    /**
     * 验证题干中的填空位格式是否正确
     * @param stem 题干文本
     * @return 是否格式正确
     */
    public static boolean validateBlankFormat(String stem) {
        if (stem == null || stem.isEmpty()) {
            return false;
        }
        
        List<Integer> indexes = extractBlankIndexes(stem);
        if (indexes.isEmpty()) {
            return false;
        }
        
        // 验证序号连续性
        for (int i = 0; i < indexes.size(); i++) {
            if (indexes.get(i) != i + 1) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 提取题干中的填空位序号
     * @param stem 题干文本
     * @return 填空位序号列表
     */
    public static List<Integer> extractBlankIndexes(String stem) {
        List<Integer> indexes = new ArrayList<>();
        if (stem == null || stem.isEmpty()) {
            return indexes;
        }
        
        Matcher matcher = BLANK_PATTERN.matcher(stem);
        while (matcher.find()) {
            try {
                int index = Integer.parseInt(matcher.group(1));
                indexes.add(index);
            } catch (NumberFormatException e) {
                // 忽略非数字序号
            }
        }
        
        return indexes;
    }
    
    /**
     * 计算题干中的填空位数量
     * @param stem 题干文本
     * @return 填空位数量
     */
    public static int countBlanks(String stem) {
        if (stem == null || stem.isEmpty()) {
            return 0;
        }
        
        Matcher matcher = BLANK_PATTERN.matcher(stem);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        
        return count;
    }
}